/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package cn.com.recloud.bbs.controller;

import cn.com.recloud.bbs.util.FileUploadUtil;
import cn.com.recloud.core.util.Result;
import cn.com.recloud.core.util.StringUtil;
import cn.hutool.core.util.URLUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @description 单文件上传和多文件上传
 * @author Herry Hong
 * @date 2020/6/11
 */
@RestController
@RequestMapping("/api/file")
@Api(tags = "文件上传")
public class FileUploadController {

    @Value("${url.backUrl}")
    private String url;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @PostMapping("/single/upload")
    @ApiOperation("单个文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件对象")
    })
    public Result singleUpload(@RequestParam(value = "file") MultipartFile file) {
        String fileUrl = fileUploadUtil.upload(file);
        if (StringUtil.isHttpStartUrl(fileUrl)){
            return new Result(fileUrl);
        }else{
            String addressUrl = new StringBuffer(url).append("/image/detail/").append(fileUrl).toString();
            return new Result(URLUtil.normalize(addressUrl));
        }
    }

    @PostMapping("/multi/upload")
    @ApiOperation("多个文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "request", value = "请求对象")
    })
    public Result multiUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        List<String> fileList = fileUploadUtil.multiFileUpload(files);
        List<String> list = new ArrayList<>();
        for (String fileName : fileList) {
            if (StringUtil.isHttpStartUrl(fileName)){
                list.add(fileName);
            }else{
                String addressUrl = new StringBuffer(url).append("/image/detail/").append(fileName).toString();
                list.add(URLUtil.normalize(addressUrl));
            }
        }
        return new Result(list);
    }
}
